import requests
import json
from lxml import etree


def get_list_video(search_key):
    '''
    获取查询列表页的 bvid_list
    :return:
    '''
    res = requests.get('https://search.bilibili.com/video?keyword={0}&order=click&duration=0&tids_1=0&page=1'.format(search_key))
    print(res.content)
    html = etree.HTML(res.content)
    html_data = html.xpath('//*[@id="video-list"]/ul/li/div/div[1]/a/@href')
    bvid_list = [data.rsplit('/', 1)[1].split('?')[0] for data in html_data]
    return bvid_list


def get_dammu(bvid):
    res = requests.get('https://api.bilibili.com/x/player/pagelist?bvid={0}'.format(bvid))
    print(res.text)
    res = json.loads(res.text)
    cid = res['data'][0]['cid']

    res = requests.get('https://api.bilibili.com/x/v1/dm/list.so?oid={0}'.format(cid))
    print(res.text)
    res.encoding = 'utf-8'

    html = etree.HTML(res.content)
    html_data = html.xpath('//i/d/text()')
    text = '\n'.join(html_data)
    with open("./text/test.txt", "a", encoding='utf-8') as f:
        f.write(text)  # 自带文件关闭功能，不需要再写f.close()


if __name__ == '__main__':
    search_key = '广东话'
    bvid_list = get_list_video(search_key)
    for bvid in bvid_list:
        get_dammu(bvid)
